package cn.ug.analyse.web.job;

import cn.ug.analyse.service.StatService;
import cn.ug.config.RedisGlobalLock;
import cn.ug.util.DateUtil;
import cn.ug.util.UF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 渠道相关数据统计
 * 必须每天执行一次
 *
 * @author zhaohg
 * @date 2018/08/07.
 */
@Component
public class ChannelJob {

    private static Logger logger = LoggerFactory.getLogger(ChannelJob.class);

    @Resource
    private RedisGlobalLock redisGlobalLock;

    @Resource
    private StatService statService;

    /**
     * 渠道数据统计
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void ChannelStatJob() {
        Date date = DateUtil.localDateToDate(LocalDate.now().minusDays(1)); //昨天0时0分0秒日期
        String key = String.format("ChannelStatJob:expiredMemberHoldJob:%s", date);
        if (redisGlobalLock.lock(key, 12, TimeUnit.HOURS)) {
            try {
                logger.info("渠道数据统计定时任务");
                logger.info(UF.getFormatDateTime(UF.getDateTime()));
                //执行任务
                //this.statChannelData(date);
                statService.statChannelData(date);
            } catch (Exception e) {
                logger.error("-------ChannelStatJob error-------");
                throw e;
            } finally {
                redisGlobalLock.unlock(key);
            }
        } else {
            logger.info("-------没有获取到锁-------");
            return;
        }
    }

}
